package com.yunang.officialweb.service.impl;

import com.yunang.officialweb.entity.TotalDesc;
import com.yunang.officialweb.mapper.DepMapper;
import com.yunang.officialweb.mapper.TotalMapper;
import com.yunang.officialweb.service.TotalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @author duan
 * @date 2022/11/29 21:30
 */
@Service
public class TotalServiceImpl implements TotalService {

    @Autowired
    private TotalMapper totalMapper;

    @Override
    public TotalDesc selectById(int id) {
        return totalMapper.selectById(id);
    }

    @Override
    public String savePic(MultipartFile file, String paths) {
        //定义存入数据库的路径
        String url = "";
        //获得文件的后缀名
        String fileName = file.getOriginalFilename();
        if (fileName!=null && !fileName.equals("")){
            //获得文件后缀
            String lastName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
            //当前时间+随机数=新的文件名
            fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000)+lastName;
            File pathFile = new File(paths);

            if (!pathFile.exists()){
                pathFile.mkdirs();
            }
            //把图片保存到文件夹
            File targetFile = new File(paths,fileName);
            try {
                //将上传的文件昔日如服务器上的指代那个文件
                file.transferTo(targetFile);
                url = paths + fileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return url;
    }
}
